<template>
  <div class="generate-plan-container">
    <div class="page-header">
      <h2>生成计划</h2>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="handleAdd">
           <el-icon><Plus /></el-icon>添加
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
     <!-- <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form" size="small">
        <div class="form-row">
           <el-form-item label="计划主题">
             <el-input v-model="searchForm.generateplanBasicTheme" placeholder="请输入计划主题" clearable />
          </el-form-item>
           <el-form-item label="订单编号">
             <el-input v-model="searchForm.generateplanBasicOrderNumber" placeholder="请输入订单编号" clearable />
          </el-form-item>
           <el-form-item label="单据日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>
        <div class="form-row form-actions">
          <el-form-item>
            <el-button type="primary" size="small" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button size="small" @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </div>
      </el-form>
     </div> -->

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        table-layout="auto"
       >
         <el-table-column type="index" label="序号" width="80" align="center" :index="indexMethod" />
         <el-table-column prop="generateplanBasicTheme" label="计划主题" min-width="15%" />
         <el-table-column prop="generateplanBasicOrderNumber" label="订单编号" min-width="15%" />
         <el-table-column prop="salesOrder" label="销售订单" min-width="12%" />
         <el-table-column prop="documentTime" label="单据时间" min-width="18%" />
         <el-table-column prop="remarks" label="备注" min-width="15%" />
         <el-table-column label="操作" min-width="12%" fixed="right">
          <template #default="scope">
             <el-button type="primary" link size="small" @click="handleEdit(scope.row)">
               <el-icon><Edit /></el-icon>修改
             </el-button>
             <el-button type="danger" link size="small" @click="handleDelete(scope.row)">
               <el-icon><Delete /></el-icon>删除
             </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
        />
      </div>
    </div>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加生产计划"
      width="80%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <!-- 添加表单部分 -->
      <div class="add-form-section">
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="140px"
          label-position="right"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="计划主题" prop="generateplanBasicTheme">
                <el-input v-model="addForm.generateplanBasicTheme" placeholder="请输入计划主题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单编号" prop="generateplanBasicOrderNumber">
                <el-input 
                  v-model="addForm.generateplanBasicOrderNumber" 
                  placeholder="请点击生成订单编号"
                  @click="handleOrderCodeClick"
                  readonly
                  style="cursor: pointer"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="销售订单" prop="salesOrder">
                <el-input 
                  v-model="addForm.salesOrder" 
                  placeholder="请选择销售订单"
                  @click="openOrderDialog('add')"
                  readonly
                  style="cursor: pointer"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据时间" prop="documentTime">
                <el-date-picker
                  v-model="addForm.documentTime"
                  type="datetime"
                  placeholder="请选择单据时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="addForm.remarks"
              type="textarea"
              placeholder="请输入备注信息"
              :rows="3"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 生产物品显示部分 -->
      <div class="generate-items-section">
        <div class="section-header">
          <h4>生产物品</h4>
          <div class="header-buttons">
            <el-button 
              size="small" 
              type="success" 
              @click="handleAddItem"
              icon="Plus"
            >
              新增
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="fetchGenerateItemsData"
              :loading="generateItemsLoading"
            >
              刷新
            </el-button>
          </div>
        </div>
        
        <div class="items-table-wrapper">
          <el-table
            v-loading="generateItemsLoading"
            :data="generateItemsData"
            border
            stripe
            style="width: 100%"
            size="small"
            max-height="300"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="itemNumber" label="物品编号" min-width="120" />
            <el-table-column prop="itemName" label="物品名称" min-width="120" />
            <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="itemCategory" label="物品类别" min-width="100" />
            <el-table-column prop="itemClassification" label="物品分类" min-width="100" />
            <el-table-column prop="brand" label="品牌" min-width="100" />
            <el-table-column prop="orderName" label="订单名称" min-width="120" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="handleEditItem(scope.row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="danger" link size="small" @click="handleDeleteItem(scope.row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 生产物品分页 -->
          <div class="items-pagination">
            <el-pagination
              v-model:current-page="generateItemsPagination.currentPage"
              v-model:page-size="generateItemsPagination.pageSize"
              :page-sizes="[5, 10, 20]"
              layout="total, sizes, prev, pager, next"
              :total="generateItemsPagination.total"
              @size-change="handleGenerateItemsSizeChange"
              @current-change="handleGenerateItemsCurrentChange"
              small
            />
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增生产物品对话框 -->
    <el-dialog
      v-model="addItemDialogVisible"
      title="新增生产物品"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="addItemFormRef"
        :model="addItemForm"
        :rules="addItemFormRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物品编号" prop="itemNumber">
              <el-input 
                v-model="addItemForm.itemNumber" 
                placeholder="请点击生成物品编号"
                @click="handleItemCodeClick"
                readonly
                style="cursor: pointer"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品名称" prop="itemName">
              <el-input v-model="addItemForm.itemName" placeholder="请输入物品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specificationModel">
              <el-input v-model="addItemForm.specificationModel" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="addItemForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物品类别" prop="itemCategory">
              <el-input v-model="addItemForm.itemCategory" placeholder="请输入物品类别" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品分类" prop="itemClassification">
              <el-input v-model="addItemForm.itemClassification" placeholder="请输入物品分类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="addItemForm.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单名称" prop="orderName">
              <el-select 
                v-model="addItemForm.orderName" 
                placeholder="请选择订单名称"
                style="width: 100%"
                filterable
                :loading="orderOptionsLoading"
              >
                <el-option
                  v-for="order in orderOptions"
                  :key="order.id"
                  :label="order.dingdanbianhao"
                  :value="order.dingdanbianhao"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddItemForm" :loading="addItemSubmitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑生产物品对话框 -->
    <el-dialog
      v-model="editItemDialogVisible"
      title="编辑生产物品"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="editItemFormRef"
        :model="editItemForm"
        :rules="editItemFormRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物品编号" prop="itemNumber">
              <el-input 
                v-model="editItemForm.itemNumber" 
                placeholder="请点击生成物品编号"
                @click="handleEditItemCodeClick"
                readonly
                style="cursor: pointer"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品名称" prop="itemName">
              <el-input v-model="editItemForm.itemName" placeholder="请输入物品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specificationModel">
              <el-input v-model="editItemForm.specificationModel" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="editItemForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物品类别" prop="itemCategory">
              <el-input v-model="editItemForm.itemCategory" placeholder="请输入物品类别" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物品分类" prop="itemClassification">
              <el-input v-model="editItemForm.itemClassification" placeholder="请输入物品分类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="editItemForm.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单名称" prop="orderName">
              <el-select 
                v-model="editItemForm.orderName" 
                placeholder="请选择订单名称"
                style="width: 100%"
                filterable
                :loading="orderOptionsLoading"
              >
                <el-option
                  v-for="order in orderOptions"
                  :key="order.id"
                  :label="order.dingdanbianhao"
                  :value="order.dingdanbianhao"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditItemForm" :loading="editItemSubmitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改生产计划"
      width="80%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <!-- 修改表单部分 -->
      <div class="add-form-section">
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="140px"
          label-position="right"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="计划主题" prop="generateplanBasicTheme">
                <el-input v-model="editForm.generateplanBasicTheme" placeholder="请输入计划主题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单编号" prop="generateplanBasicOrderNumber">
                <el-input 
                  v-model="editForm.generateplanBasicOrderNumber" 
                  placeholder="请点击生成订单编号"
                  @click="handleEditOrderCodeClick"
                  readonly
                  style="cursor: pointer"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="销售订单" prop="salesOrder">
                <el-input
                  v-model="editForm.salesOrder" 
                  placeholder="请选择销售订单"
                  @click="openOrderDialog('edit')"
                  readonly
                  style="cursor: pointer"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据时间" prop="documentTime">
                <el-date-picker
                  v-model="editForm.documentTime"
                  type="datetime"
                  placeholder="选择单据时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备注">
            <el-input
              v-model="editForm.remarks"
              type="textarea"
              placeholder="请输入备注信息"
              :rows="3"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 生产物品显示部分 -->
      <div class="generate-items-section">
        <div class="section-header">
          <h4>生产物品</h4>
          <div class="header-buttons">
            <el-button 
              size="small" 
              type="success" 
              @click="handleAddItem"
              icon="Plus"
            >
              新增
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="fetchGenerateItemsData"
              :loading="generateItemsLoading"
            >
              刷新
            </el-button>
          </div>
        </div>
        
        <div class="items-table-wrapper">
          <el-table
            v-loading="generateItemsLoading"
            :data="generateItemsData"
            border
            stripe
            style="width: 100%"
            size="small"
            max-height="300"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="itemNumber" label="物品编号" min-width="120" />
            <el-table-column prop="itemName" label="物品名称" min-width="120" />
            <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="itemCategory" label="物品类别" min-width="100" />
            <el-table-column prop="itemClassification" label="物品分类" min-width="100" />
            <el-table-column prop="brand" label="品牌" min-width="100" />
            <el-table-column prop="orderName" label="订单名称" min-width="120" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="handleEditItem(scope.row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="danger" link size="small" @click="handleDeleteItem(scope.row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 生产物品分页 -->
          <div class="items-pagination">
            <el-pagination
              v-model:current-page="generateItemsPagination.currentPage"
              v-model:page-size="generateItemsPagination.pageSize"
              :page-sizes="[5, 10, 20]"
              layout="total, sizes, prev, pager, next"
              :total="generateItemsPagination.total"
              @size-change="handleGenerateItemsSizeChange"
              @current-change="handleGenerateItemsCurrentChange"
              small
            />
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="editSubmitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单选择对话框 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="选择销售订单"
      width="80%"
      destroy-on-close
    >
      <div class="order-dialog-content">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :inline="true" size="small">
            <el-form-item label="订单编号">
              <el-input v-model="orderSearch.dingdanbianhao" placeholder="请输入订单编号" clearable />
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="orderSearch.keHuName" placeholder="请输入客户名称" clearable />
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input v-model="orderSearch.shopname" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchOrders">搜索</el-button>
              <el-button @click="resetOrderSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 订单表格 -->
        <el-table
          v-loading="orderTableLoading"
          :data="orderTableData"
          border
          stripe
          style="width: 100%"
          @row-click="selectOrder"
          highlight-current-row
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dingdanbianhao" label="订单编号" min-width="120" />
          <el-table-column prop="kehuid" label="客户名称" min-width="120" />
          <el-table-column prop="dingdanriqi" label="订单日期" min-width="120" />
          <el-table-column prop="shopname" label="商品名称" min-width="150" />
          <el-table-column prop="zongjine" label="总金额" min-width="100" />
          <el-table-column prop="zhuangtai" label="状态" min-width="80">
                <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.zhuangtai)" size="small">
                {{ getOrderStatusText(scope.row.zhuangtai) }}
                  </el-tag>
                </template>
              </el-table-column>
          <el-table-column prop="beizhu" label="备注" min-width="120" />
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="selectOrder(scope.row)">
                选择
              </el-button>
                </template>
              </el-table-column>
            </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="orderPagination.currentPage"
            v-model:page-size="orderPagination.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="orderPagination.total"
            @size-change="handleOrderSizeChange"
            @current-change="handleOrderCurrentChange"
            small
          />
        </div>
      </div>
    </el-dialog>

    <!-- 订单编号规则生成对话框 -->
    <el-dialog
      v-model="orderCodeRuleDialogVisible"
      title="单据编码(新建)"
      width="800px"
      :before-close="handleOrderCodeRuleDialogClose"
    >
      <el-form
        ref="orderCodeRuleFormRef"
        :model="orderCodeRuleFormData"
        :rules="orderCodeRuleFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务名称" prop="businessName">
              <el-select
                v-model="orderCodeRuleFormData.businessName"
                placeholder="请选择业务名称"
                style="width: 100%"
              >
                <el-option label="生产计划" value="生产计划" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-select
                v-model="orderCodeRuleFormData.ruleName"
                placeholder="请选择规则名称"
                style="width: 100%"
              >
                <el-option label="订单管理" value="订单管理" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据字段" prop="documentField">
              <el-select
                v-model="orderCodeRuleFormData.documentField"
                placeholder="请选择单据字段"
                style="width: 100%"
              >
                <el-option label="订单编号" value="订单编号" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期排序字段" prop="dateField">
              <el-select
                v-model="orderCodeRuleFormData.dateField"
                placeholder="请选择日期字段"
                style="width: 100%"
              >
                <el-option label="单据时间" value="单据时间" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input 
                v-model="orderCodeRuleFormData.prefix" 
                placeholder="请输入前缀" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="ruleType">
              <el-radio-group v-model="orderCodeRuleFormData.ruleType">
                <el-radio label="年">年</el-radio>
                <el-radio label="年月">年月</el-radio>
                <el-radio label="年月日">年月日</el-radio>
                <el-radio label="无">无</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号位数" prop="numberLength">
              <el-input-number 
                v-model="orderCodeRuleFormData.numberLength" 
                :min="1" 
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增长类型" prop="incrementType">
              <el-select
                v-model="orderCodeRuleFormData.incrementType"
                placeholder="请选择增长类型"
                style="width: 100%"
              >
                <el-option label="编号每日从1开始自增" value="编号每日从1开始自增" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="连接符号">
          <el-input 
            v-model="orderCodeRuleFormData.connector" 
            placeholder="请输入连接符号" 
          />
        </el-form-item>

        <div class="code-preview-section">
          <h4>编码预览</h4>
          <div class="preview-code">
            {{ generateOrderPreviewCode() }}
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleOrderCodeRuleCancel">取消</el-button>
          <el-button type="primary" @click="handleOrderCodeRuleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { APIs, DingDanAPI } from '@/Http/http'
import axios from 'axios'

// 表格加载状态
const tableLoading = ref(false)

// 搜索表单
interface SearchForm {
  generateplanBasicTheme: string;
  generateplanBasicOrderNumber: string;
  dateRange: string[];
}

const searchForm = reactive<SearchForm>({
  generateplanBasicTheme: '',
  generateplanBasicOrderNumber: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 生产物品相关
const generateItemsLoading = ref(false)
const generateItemsData = ref<any[]>([])
const generateItemsPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 添加对话框相关
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addFormRef = ref()

// 新增生产物品对话框相关
const addItemDialogVisible = ref(false)
const addItemSubmitLoading = ref(false)
const addItemFormRef = ref()

// 编辑生产物品对话框相关
const editItemDialogVisible = ref(false)
const editItemSubmitLoading = ref(false)
const editItemFormRef = ref()
const currentEditItemId = ref(0)

// 订单选项数据
const orderOptions = ref<any[]>([])
const orderOptionsLoading = ref(false)

// 修改对话框相关
const editDialogVisible = ref(false)
const editSubmitLoading = ref(false)
const editFormRef = ref()
const currentEditId = ref(0)

// 订单选择对话框相关
const orderDialogVisible = ref(false)
const orderTableLoading = ref(false)
const orderTableData = ref<any[]>([])
const orderDialogMode = ref<'add' | 'edit'>('add') // 区分是添加还是修改模式

// 订单编号规则生成对话框相关
const orderCodeRuleDialogVisible = ref(false)
const orderCodeRuleFormRef = ref()
const orderCodeRuleFormData = reactive({
  businessName: '生产计划',
  ruleName: '订单管理',
  documentField: '订单编号',
  dateField: '单据时间',
  prefix: 'DD',
  ruleType: '年月日',
  numberLength: 5,
  incrementType: '编号每日从1开始自增',
  connector: ''
})
const currentOrderCodeMode = ref<'add' | 'edit' | 'item' | 'editItem'>('add') // 区分是添加、修改、新增物品还是编辑物品编号生成模式

// 订单搜索表单
const orderSearch = reactive({
  dingdanbianhao: '',
  keHuName: '',
  shopname: ''
})

// 订单分页配置
const orderPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 添加表单数据
const addForm = reactive({
  generateplanBasicTheme: '',
  generateplanBasicOrderNumber: '',
  salesOrder: '',
  documentTime: '',
  remarks: ''
})

// 修改表单数据
const editForm = reactive({
  generateplanBasicTheme: '',
  generateplanBasicOrderNumber: '',
  salesOrder: '',
  documentTime: '',
  remarks: ''
})

// 新增生产物品表单数据
const addItemForm = reactive({
  itemNumber: '',
  itemName: '',
  specificationModel: '',
  unit: '',
  itemCategory: '',
  itemClassification: '',
  brand: '',
  orderName: '',
  isDel: false,
  generateplanBasicId: null
})

// 编辑生产物品表单数据
const editItemForm = reactive({
  itemNumber: '',
  itemName: '',
  specificationModel: '',
  unit: '',
  itemCategory: '',
  itemClassification: '',
  brand: '',
  orderName: '',
  isDel: false,
  generateplanBasicId: null
})

// 表单验证规则
const addFormRules = {
  generateplanBasicTheme: [
    { required: true, message: '请输入计划主题', trigger: 'blur' }
  ],
  generateplanBasicOrderNumber: [
    { required: true, message: '请输入订单编号', trigger: 'blur' }
  ],
  salesOrder: [
    { required: true, message: '请输入销售订单', trigger: 'blur' }
  ],
  documentTime: [
    { required: true, message: '请选择单据时间', trigger: 'change' }
  ]
}

// 修改表单验证规则（与添加表单相同）
const editFormRules = {
  generateplanBasicTheme: [
    { required: true, message: '请输入计划主题', trigger: 'blur' }
  ],
  generateplanBasicOrderNumber: [
    { required: true, message: '请输入订单编号', trigger: 'blur' }
  ],
  salesOrder: [
    { required: true, message: '请输入销售订单', trigger: 'blur' }
  ],
  documentTime: [
    { required: true, message: '请选择单据时间', trigger: 'change' }
  ]
}

// 新增生产物品表单验证规则
const addItemFormRules = {
  itemNumber: [
    { required: true, message: '请输入物品编号', trigger: 'blur' }
  ],
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' }
  ],
  specificationModel: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  itemCategory: [
    { required: true, message: '请输入物品类别', trigger: 'blur' }
  ]
}

// 编辑生产物品表单验证规则
const editItemFormRules = {
  itemNumber: [
    { required: true, message: '请输入物品编号', trigger: 'blur' }
  ],
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' }
  ],
  specificationModel: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  itemCategory: [
    { required: true, message: '请输入物品类别', trigger: 'blur' }
  ]
}

// 订单编号规则表单验证规则
const orderCodeRuleFormRules = {
  businessName: [
    { required: true, message: '请选择业务名称', trigger: 'change' }
  ],
  ruleName: [
    { required: true, message: '请选择规则名称', trigger: 'change' }
  ],
  documentField: [
    { required: true, message: '请选择单据字段', trigger: 'change' }
  ],
  prefix: [
    { required: true, message: '请输入前缀', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  numberLength: [
    { required: true, message: '请输入编号位数', trigger: 'blur' }
  ]
}

// API接口函数                                                                                                                                                                                                              
const getGenerateplanBasicData = async () => {
  try {
    const params: any = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize
    }
    
    // 添加搜索参数
    if (searchForm.generateplanBasicTheme) {
      params.generateplanBasicTheme = searchForm.generateplanBasicTheme
    }
    if (searchForm.generateplanBasicOrderNumber) {
      params.generateplanBasicOrderNumber = searchForm.generateplanBasicOrderNumber
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const response = await APIs.get('/api/GenerateplanBasic/ShowGenerateplanBasic', {
      params
    })
    return response.data
  } catch (error) {
   
    ElMessage.error('获取数据失败，请稍后重试')
    throw error
  }
}

// 添加记录的API函数
const addGenerateplanBasic = async (data: any) => {
  try {
    const response = await APIs.post('/api/GenerateplanBasic/AddGenerateplanBasic', data)
    return response.data
  } catch (error) {
    throw error
  }
}

// 删除记录的API函数
const deleteGenerateplanBasic = async (generateplanBasicId: number) => {
  try {
    const response = await APIs.post('/api/GenerateplanBasic/DeleteGenerateplanBasic', {
      generateplanBasicId: generateplanBasicId
    })
    return response.data
  } catch (error) {
    // console.error('删除API调用失败:', error)
    throw error
  }
}

// 修改记录的API函数
const updateGenerateplanBasic = async (data: any) => {
  try {
    const response = await APIs.post('/api/GenerateplanBasic/UpdateGenerateplanBasic', data)
    return response.data
  } catch (error) {
    // console.error('修改API调用失败:', error)
    throw error
  }
}

// 获取生产物品数据的API函数
const getGenerateItemsData = async () => {
  try {
    const params: any = {
      PageIndex: generateItemsPagination.currentPage,
      PageSize: generateItemsPagination.pageSize
    }
    
    const response = await APIs.get('/api/GenerateItems/ShowGenerateItems', {
      params
    })
    return response.data
  } catch (error) {
    ElMessage.error('获取生产物品数据失败，请稍后重试')
    throw error
  }
}

// 添加生产物品的API函数
const addGenerateItem = async (data: any) => {
  try {
    const response = await APIs.post('/api/GenerateItems/AddGenerateItem', data)
    return response.data
  } catch (error) {
    throw error
  }
}

// 修改生产物品的API函数
const updateGenerateItem = async (data: any) => {
  try {
    const response = await APIs.put('/api/GenerateItems/UpdateGenerateItem', data)
    return response.data
  } catch (error) {
    throw error
  }
}

// 删除生产物品的API函数
const deleteGenerateItem = async (generateItemsId: number) => {
  try {
    const response = await APIs.delete(`/api/GenerateItems/DeleteGenerateItem/${generateItemsId}`)
    return response.data
  } catch (error) {
    throw error
  }
}

// 获取订单选项数据的函数
const fetchOrderOptions = async () => {
  orderOptionsLoading.value = true
  try {
    // 使用已有的订单数据获取函数，但不需要分页参数
    const params = {
      PageIndex: 1,
      PageSize: 100  // 获取更多数据用于下拉选择
    }
    
    const response = await DingDanAPI.get('/api/DingDan/QueryDingDan', {
      params
    })
    
    // 处理响应数据格式
    let dataArray = []
    if (response && response.data && Array.isArray(response.data.data)) {
      dataArray = response.data.data
    } else if (response && Array.isArray(response.data)) {
      dataArray = response.data
    } else if (response && Array.isArray(response)) {
      dataArray = response
    }
    
    // 映射订单数据
    orderOptions.value = dataArray.map((item: any) => ({
      id: item.id || item.Id || '',
      dingdanbianhao: item.dingdanbianhao || item.dingDanBianHao || item.DingDanBianHao || '',
      keHuName: item.keHuName || item.kehuid || item.keHuId || item.KeHuId || '',
      shopname: item.shopname || item.shopName || item.ShopName || ''
    }))
    
  } catch (error) {
    console.error('获取订单选项失败:', error)
    ElMessage.error('获取订单列表失败')
    orderOptions.value = []
  } finally {
    orderOptionsLoading.value = false
  }
}

// 获取订单数据的API函数
const getDingDanData = async () => {
  try {
    const params: any = {
      PageIndex: orderPagination.currentPage,
      PageSize: orderPagination.pageSize
    }
    
    // 添加搜索参数
    if (orderSearch.dingdanbianhao) {
      params.dingdanbianhao = orderSearch.dingdanbianhao
    }
    if (orderSearch.keHuName) {
      params.keHuName = orderSearch.keHuName
    }
    if (orderSearch.shopname) {
      params.shopname = orderSearch.shopname
    }
    
    // 使用 DingDanAPI 实例调用接口
    const response = await DingDanAPI.get('/api/DingDan/QueryDingDan', {
      params
    })
    return response.data
  } catch (error) {
    // console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败，请稍后重试')
    throw error
  }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
  fetchGenerateItemsData()
})

// 获取数据
const fetchData = async () => {
  tableLoading.value = true
  
  try {
    const response = await getGenerateplanBasicData()
    
    // 处理不同的响应格式
    let dataArray = []
    let total = 0
    
    if (response && Array.isArray(response.data)) {
      dataArray = response.data
      total = response.totalCount || response.total || dataArray.length
    } else if (response && Array.isArray(response)) {
      dataArray = response
      total = dataArray.length
    } else if (response && response.data && Array.isArray(response.data.data)) {
      dataArray = response.data.data
      total = response.data.totalCount || response.data.total || dataArray.length
    }
    
     if (dataArray.length > 0) {
       // 直接使用API返回的数据字段，只保留数据库表中的字段
       tableData.value = dataArray.map((item: any) => ({
         generateplanBasicId: item.generateplanBasicId || '',
         generateplanBasicTheme: item.generateplanBasicTheme || '',
         generateplanBasicOrderNumber: item.generateplanBasicOrderNumber || '',
         salesOrder: item.salesOrder || '',
         documentTime: item.documentTime ? item.documentTime.replace('T', ' ').substring(0, 19) : '',
         remarks: item.remarks || '',
         orderId: item.orderId || ''
       }))
       
       // 设置分页信息
       pagination.total = total
     } else {
       tableData.value = []
       pagination.total = 0
   
     }
  } catch (error) {
  
    // 如果API调用失败，显示空数据
    tableData.value = []
    pagination.total = 0
  } finally {
    tableLoading.value = false
  }
}

// 获取生产物品数据
const fetchGenerateItemsData = async () => {
  generateItemsLoading.value = true
  
  try {
    console.log('📡 开始获取生产物品数据...')
    const response = await getGenerateItemsData()
    console.log('📡 生产物品API响应:', response)
    
    // 处理不同的响应格式
    let dataArray = []
    let total = 0
    
    if (response && Array.isArray(response.data)) {
      dataArray = response.data
      total = response.totalCount || response.total || dataArray.length
    } else if (response && Array.isArray(response)) {
      dataArray = response
      total = dataArray.length
    } else if (response && response.data && Array.isArray(response.data.data)) {
      dataArray = response.data.data
      total = response.data.totalCount || response.data.total || dataArray.length
    }
    
    console.log('📊 解析出的数据数组:', dataArray)
    console.log('📊 数据总数:', total)
    
    if (dataArray.length > 0) {
      // 根据API返回的数据结构映射字段
      generateItemsData.value = dataArray.map((item: any) => ({
        generateItemsId: item.generateItemsId || '',
        itemNumber: item.itemNumber || '',
        itemName: item.itemName || '',
        specificationModel: item.specificationModel || '',
        unit: item.unit || '',
        itemCategory: item.itemCategory || '',
        itemClassification: item.itemClassification || '',
        brand: item.brand || '',
        orderName: item.orderName || '',
        isDel: item.isDel || false,
        generateplanBasicId: item.generateplanBasicId || ''
      }))
      
      generateItemsPagination.total = total
      console.log('✅ 生产物品数据更新完成，条数:', generateItemsData.value.length)
    } else {
      generateItemsData.value = []
      generateItemsPagination.total = 0
      console.log('⚠️ 没有获取到生产物品数据')
    }
  } catch (error) {
    console.error('❌ 获取生产物品数据失败:', error)
    generateItemsData.value = []
    generateItemsPagination.total = 0
  } finally {
    generateItemsLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.generateplanBasicTheme = ''
  searchForm.generateplanBasicOrderNumber = ''
  searchForm.dateRange = []
  handleSearch()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 计算序号的方法（考虑分页）
const indexMethod = (index: number) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1
}

// 生产物品分页处理
const handleGenerateItemsSizeChange = (size: number) => {
  generateItemsPagination.pageSize = size
  fetchGenerateItemsData()
}

const handleGenerateItemsCurrentChange = (page: number) => {
  generateItemsPagination.currentPage = page
  fetchGenerateItemsData()
}

// 处理添加
const handleAdd = () => {
  // 重置表单
  addForm.generateplanBasicTheme = ''
  addForm.generateplanBasicOrderNumber = ''
  addForm.salesOrder = ''
  addForm.documentTime = ''
  addForm.remarks = ''
  
  // 显示对话框
  addDialogVisible.value = true
  
  // 加载生产物品数据
  fetchGenerateItemsData()
}

// 处理新增生产物品
const handleAddItem = async () => {
  // 重置表单
  addItemForm.itemNumber = ''
  addItemForm.itemName = ''
  addItemForm.specificationModel = ''
  addItemForm.unit = ''
  addItemForm.itemCategory = ''
  addItemForm.itemClassification = ''
  addItemForm.brand = ''
  addItemForm.orderName = ''
  addItemForm.isDel = false
  addItemForm.generateplanBasicId = null
  
  // 显示对话框
  addItemDialogVisible.value = true
  
  // 加载订单选项数据
  await fetchOrderOptions()
}

// 提交添加表单
const submitAddForm = async () => {
  try {
    // 表单验证
    const valid = await addFormRef.value?.validate()
    if (!valid) return

    submitLoading.value = true
    
    // 准备提交数据
    const submitData = {
      generateplanBasicTheme: addForm.generateplanBasicTheme,
      generateplanBasicOrderNumber: addForm.generateplanBasicOrderNumber,
      salesOrder: addForm.salesOrder,
      documentTime: addForm.documentTime ? new Date(addForm.documentTime).toISOString() : '',
      remarks: addForm.remarks
    }

    // 调用API
    const result = await addGenerateplanBasic(submitData)
    // 如果没有抛出异常，说明添加成功
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    // 重新加载数据
    await fetchData()
    
  } catch (error) {
   
    ElMessage.error('添加失败，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

// 提交新增生产物品表单
const submitAddItemForm = async () => {
  try {
    // 表单验证
    const valid = await addItemFormRef.value?.validate()
    if (!valid) return

    addItemSubmitLoading.value = true
    
    // 准备提交数据
    const submitData = {
      itemNumber: addItemForm.itemNumber,
      itemName: addItemForm.itemName,
      specificationModel: addItemForm.specificationModel,
      unit: addItemForm.unit,
      itemCategory: addItemForm.itemCategory,
      itemClassification: addItemForm.itemClassification,
      brand: addItemForm.brand,
      orderName: addItemForm.orderName,
      isDel: addItemForm.isDel,
      generateplanBasicId: addItemForm.generateplanBasicId || null
    }

    // 调用API
    await addGenerateItem(submitData)
    ElMessage.success('新增生产物品成功')
    addItemDialogVisible.value = false
    
    // 重新加载生产物品数据
    await fetchGenerateItemsData()
    
  } catch (error) {
    ElMessage.error('新增生产物品失败，请稍后重试')
  } finally {
    addItemSubmitLoading.value = false
  }
}

// 提交编辑生产物品表单
const submitEditItemForm = async () => {
  try {
    // 表单验证
    const valid = await editItemFormRef.value?.validate()
    if (!valid) return

    editItemSubmitLoading.value = true
    
    // 准备提交数据
    const submitData = {
      generateItemsId: currentEditItemId.value,
      itemNumber: editItemForm.itemNumber,
      itemName: editItemForm.itemName,
      specificationModel: editItemForm.specificationModel,
      unit: editItemForm.unit,
      itemCategory: editItemForm.itemCategory,
      itemClassification: editItemForm.itemClassification,
      brand: editItemForm.brand,
      orderName: editItemForm.orderName,
      isDel: false,  // 强制设置为false
      generateplanBasicId: null  // 强制设置为null
    }

    console.log('🔧 提交修改数据:', submitData)

    // 调用API
    const result = await updateGenerateItem(submitData)
    console.log('✅ 修改API响应:', result)
    
    ElMessage.success('修改生产物品成功')
    editItemDialogVisible.value = false
    
    // 重新加载生产物品数据
    console.log('🔄 开始重新加载生产物品数据...')
    // 重置分页到第一页，确保能看到修改的数据
    generateItemsPagination.currentPage = 1
    await fetchGenerateItemsData()
    console.log('✅ 生产物品数据重新加载完成')
    
  } catch (error) {
    console.error('❌ 修改生产物品失败:', error)
    ElMessage.error('修改生产物品失败，请稍后重试')
  } finally {
    editItemSubmitLoading.value = false
  }
}

// 处理修改
const handleEdit = async (row: any) => {
  // console.log('🔧 开始修改记录:', row)
  
  // 存储当前编辑的ID
  currentEditId.value = row.generateplanBasicId
  
  // 反填数据到修改表单
  editForm.generateplanBasicTheme = row.generateplanBasicTheme || ''
  editForm.generateplanBasicOrderNumber = row.generateplanBasicOrderNumber || ''
  editForm.salesOrder = row.salesOrder || ''
  editForm.documentTime = row.documentTime ? row.documentTime.replace('T', ' ').substring(0, 19) : ''
  editForm.remarks = row.remarks || ''
  
  // console.log('📝 已反填修改表单数据:', editForm)
  
  // 打开修改对话框
  editDialogVisible.value = true
  
  // 加载生产物品数据
  await fetchGenerateItemsData()
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除计划主题为"${row.generateplanBasicTheme}"的记录吗？`,
    '删除确认',
    {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
    }
  ).then(async () => {
    try {
      // console.log('🗑️ 开始删除记录，ID:', row.generateplanBasicId)
      
      // 调用删除API
      await deleteGenerateplanBasic(row.generateplanBasicId)
      
      // console.log('✅ 删除成功')
      ElMessage.success('删除成功')
      
      // 删除成功后重新获取数据
      await fetchData()
      
    } catch (error) {
      // console.error('❌ 删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交修改表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    editSubmitLoading.value = true
    // console.log('🔄 开始提交修改数据...')
    
    // 构造提交数据
    const submitData = {
      generateplanBasicId: currentEditId.value,
      generateplanBasicTheme: editForm.generateplanBasicTheme,
      generateplanBasicOrderNumber: editForm.generateplanBasicOrderNumber,
      salesOrder: editForm.salesOrder,
      documentTime: editForm.documentTime ? new Date(editForm.documentTime).toISOString() : '',
      remarks: editForm.remarks
    }
    
    // console.log('📤 修改提交数据:', submitData)
    
    // 调用修改API
    await updateGenerateplanBasic(submitData)
    
    // console.log('✅ 修改成功')
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    
    // 重新加载数据
    await fetchData()
    
  } catch (error) {
    // console.error('❌ 修改失败:', error)
    ElMessage.error('修改失败，请稍后重试')
  } finally {
    editSubmitLoading.value = false
  }
}

// 打开订单选择对话框
const openOrderDialog = (mode: 'add' | 'edit' = 'add') => {
  orderDialogMode.value = mode
  orderDialogVisible.value = true
  // 重置搜索条件和分页
  orderSearch.dingdanbianhao = ''
  orderSearch.keHuName = ''
  orderSearch.shopname = ''
  orderPagination.currentPage = 1
  // 获取订单数据
  fetchOrderData()
}

// 获取订单数据
const fetchOrderData = async () => {
  orderTableLoading.value = true
  
  try {
    const response = await getDingDanData()
    
    // console.log('🔍 订单API返回的原始数据:', response)
    
    // 处理不同的响应格式
    let dataArray = []
    let total = 0
    
    if (response && Array.isArray(response.data)) {
      dataArray = response.data
      total = response.totalCount || response.total || dataArray.length
    } else if (response && Array.isArray(response)) {
      dataArray = response
      total = dataArray.length
    } else if (response && response.data && Array.isArray(response.data.data)) {
      dataArray = response.data.data
      total = response.data.totalCount || response.data.total || dataArray.length
    } else if (response && response.data) {
      // 尝试直接使用response.data
      dataArray = Array.isArray(response.data) ? response.data : [response.data]
      total = response.totalCount || response.total || dataArray.length
    } else if (response) {
      // 如果response本身就是数据
      dataArray = Array.isArray(response) ? response : [response]
      total = dataArray.length
    }
    
    // console.log('🔍 解析出的数据数组:', dataArray)
    // console.log('🔍 数据总数:', total)
    
    if (dataArray.length > 0) {
      // 根据数据库结构映射字段
      orderTableData.value = dataArray.map((item: any) => ({
        id: item.id || item.Id || '',
        dingdanbianhao: item.dingdanbianhao || item.dingDanBianHao || item.DingDanBianHao || '',
        kehuid: item.keHuName || item.kehuid || item.keHuId || item.KeHuId || '',
        dingdanriqi: item.dingdanriqi || item.dingDanRiQi || item.DingDanRiQi ? 
          (item.dingdanriqi || item.dingDanRiQi || item.DingDanRiQi).replace('T', ' ').substring(0, 19) : '',
        shopname: item.shopname || item.shopName || item.ShopName || '',
        zongjine: item.zongjine || item.zongJinE || item.ZongJinE || 0,
        zhuangtai: item.zhuangtai || item.zhuangTai || item.ZhuangTai || 0,
        beizhu: item.beizhu || item.beiZhu || item.BeiZhu || ''
      }))
      
      // console.log('🔍 处理后的订单数据:', orderTableData.value)
      
      orderPagination.total = total
    } else {
      orderTableData.value = []
      orderPagination.total = 0
    }
  } catch (error) {
    orderTableData.value = []
    orderPagination.total = 0
  } finally {
    orderTableLoading.value = false
  }
}

// 搜索订单
const searchOrders = () => {
  orderPagination.currentPage = 1
  fetchOrderData()
}

// 重置订单搜索
const resetOrderSearch = () => {
  orderSearch.dingdanbianhao = ''
  orderSearch.keHuName = ''
  orderSearch.shopname = ''
  searchOrders()
}

// 处理订单分页大小变化
const handleOrderSizeChange = (size: number) => {
  orderPagination.pageSize = size
  fetchOrderData()
}

// 处理订单当前页变化
const handleOrderCurrentChange = (page: number) => {
  orderPagination.currentPage = page
  fetchOrderData()
}

// 选择订单
const selectOrder = (row: any) => {
  // 根据当前模式填充对应表单
  if (orderDialogMode.value === 'add') {
    addForm.salesOrder = row.dingdanbianhao
  } else if (orderDialogMode.value === 'edit') {
    editForm.salesOrder = row.dingdanbianhao
  }
  
  // 关闭对话框
  orderDialogVisible.value = false
  ElMessage.success('已选择订单：' + row.dingdanbianhao)
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info'     // 待处理
    case 1: return 'success'  // 已确认
    case 2: return 'success'  // 已完成
    case 3: return 'danger'   // 已取消
    default: return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 0: return '待处理'
    case 1: return '已确认'
    case 2: return '已完成'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 订单编号规则生成相关方法
const handleOrderCodeClick = () => {
  currentOrderCodeMode.value = 'add'
  orderCodeRuleDialogVisible.value = true
  resetOrderCodeRuleForm()
}

const handleEditOrderCodeClick = () => {
  currentOrderCodeMode.value = 'edit'
  orderCodeRuleDialogVisible.value = true
  resetOrderCodeRuleForm()
}

const handleItemCodeClick = () => {
  currentOrderCodeMode.value = 'item'
  orderCodeRuleDialogVisible.value = true
  resetOrderCodeRuleForm()
}

const handleEditItemCodeClick = () => {
  currentOrderCodeMode.value = 'editItem'
  orderCodeRuleDialogVisible.value = true
  resetOrderCodeRuleForm()
}

// 处理编辑生产物品
const handleEditItem = async (row: any) => {
  // 存储当前编辑的ID
  currentEditItemId.value = row.generateItemsId
  
  // 反填数据到编辑表单，确保默认值正确
  editItemForm.itemNumber = row.itemNumber || ''
  editItemForm.itemName = row.itemName || ''
  editItemForm.specificationModel = row.specificationModel || ''
  editItemForm.unit = row.unit || ''
  editItemForm.itemCategory = row.itemCategory || ''
  editItemForm.itemClassification = row.itemClassification || ''
  editItemForm.brand = row.brand || ''
  editItemForm.orderName = row.orderName || ''
  editItemForm.isDel = false  // 确保默认为false
  editItemForm.generateplanBasicId = null  // 确保默认为null
  
  // 显示对话框
  editItemDialogVisible.value = true
  
  // 加载订单选项数据
  await fetchOrderOptions()
}

// 处理删除生产物品
const handleDeleteItem = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除物品编号为"${row.itemNumber}"的记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用删除API
      await deleteGenerateItem(row.generateItemsId)
      
      ElMessage.success('删除成功')
      
      // 删除成功后重新获取数据
      await fetchGenerateItemsData()
      
    } catch (error) {
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleOrderCodeRuleDialogClose = () => {
  resetOrderCodeRuleForm()
}

const handleOrderCodeRuleCancel = () => {
  orderCodeRuleDialogVisible.value = false
  resetOrderCodeRuleForm()
}

const resetOrderCodeRuleForm = () => {
  Object.assign(orderCodeRuleFormData, {
    businessName: '生产计划',
    ruleName: '订单管理',
    documentField: '订单编号',
    dateField: '单据时间',
    prefix: 'DD',
    ruleType: '年月日',
    numberLength: 5,
    incrementType: '编号每日从1开始自增',
    connector: ''
  })
  orderCodeRuleFormRef.value?.clearValidate()
}

const generateOrderPreviewCode = () => {
  const { prefix, ruleType, numberLength, connector } = orderCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  const numberPart = '1'.padStart(numberLength, '0')
  
  let code = prefix || ''
  if (datePart && code) {
    code += connector + datePart
  } else if (datePart) {
    code += datePart
  }
  
  if (numberPart && code) {
    code += connector + numberPart
  } else if (numberPart) {
    code += numberPart
  }
  
  return code || '预览编码'
}

// 生成真正的自增订单编号
const generateActualOrderCode = async () => {
  const { prefix, ruleType, numberLength, connector } = orderCodeRuleFormData
  const now = new Date()
  
  let datePart = ''
  switch (ruleType) {
    case '年':
      datePart = now.getFullYear().toString()
      break
    case '年月':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0')
      break
    case '年月日':
      datePart = now.getFullYear().toString() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0')
      break
    case '无':
      datePart = ''
      break
  }
  
  // 构造前缀部分（不包含序号）
  let codePrefix = prefix || ''
  if (datePart) {
    if (codePrefix && connector) {
      codePrefix += connector + datePart
    } else if (codePrefix) {
      codePrefix += datePart
    } else {
      codePrefix = datePart
    }
  }
  
  try {
    // 查询现有的订单编号，找到最大的序号
    let maxNumber = 0
    
    // 遍历现有数据查找最大序号
    for (const item of tableData.value) {
      const orderNumber = item.generateplanBasicOrderNumber || ''
      
      // 构建匹配模式，用于检查是否符合当前编码规则
      const expectedPrefix = codePrefix
      
      // 检查是否以当前前缀开头
      if (orderNumber.startsWith(expectedPrefix)) {
        // 提取序号部分
        let numberPart = ''
        
        if (connector && codePrefix) {
          // 如果有连接符，序号在最后一个连接符之后
          const lastConnectorIndex = orderNumber.lastIndexOf(connector)
          if (lastConnectorIndex !== -1) {
            numberPart = orderNumber.substring(lastConnectorIndex + connector.length)
          }
        } else {
          // 如果没有连接符，序号就是前缀之后的部分
          numberPart = orderNumber.substring(expectedPrefix.length)
        }
        
        // 尝试解析为数字
        const currentNumber = parseInt(numberPart, 10)
        if (!isNaN(currentNumber) && currentNumber > maxNumber) {
          maxNumber = currentNumber
        }
      }
    }
    
    // 下一个序号
    const nextNumber = maxNumber + 1
    const numberPart = nextNumber.toString().padStart(numberLength, '0')
    
    // 拼接最终编号
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
    
  } catch (error) {
    console.error('生成订单编号失败:', error)
    // 如果出错，返回默认编号
    const numberPart = '1'.padStart(numberLength, '0')
    if (codePrefix && connector) {
      return codePrefix + connector + numberPart
    } else {
      return codePrefix + numberPart
    }
  }
}

const handleOrderCodeRuleSave = async () => {
  if (!orderCodeRuleFormRef.value) return
  
  try {
    await orderCodeRuleFormRef.value.validate()
    
    // 生成真正的自增编码
    const generatedCode = await generateActualOrderCode()
    
    if (currentOrderCodeMode.value === 'add') {
      addForm.generateplanBasicOrderNumber = generatedCode
      ElMessage.success('订单编号已生成: ' + generatedCode)
    } else if (currentOrderCodeMode.value === 'edit') {
      editForm.generateplanBasicOrderNumber = generatedCode
      ElMessage.success('订单编号已生成: ' + generatedCode)
    } else if (currentOrderCodeMode.value === 'item') {
      addItemForm.itemNumber = generatedCode
      ElMessage.success('物品编号已生成: ' + generatedCode)
    } else if (currentOrderCodeMode.value === 'editItem') {
      editItemForm.itemNumber = generatedCode
      ElMessage.success('物品编号已生成: ' + generatedCode)
    }
    
    orderCodeRuleDialogVisible.value = false
  } catch (error) {
    console.error('生成编号失败:', error)
    ElMessage.error('请检查表单输入')
  }
}
</script>

<style scoped>
.generate-plan-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100%;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-area {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  justify-content: space-between;
  margin-bottom: 10px;
}

.form-row .el-form-item {
  margin-right: 0;
  margin-bottom: 10px;
  flex: 1;
  min-width: 200px;
  max-width: 25%;
}

.form-row .el-input,
.form-row .el-select,
.form-row .el-date-picker {
  width: 90%;
}

.form-actions {
  justify-content: flex-end;
}

.form-actions .el-form-item {
  min-width: auto;
  max-width: none;
}

.table-container {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-x: auto;
  width: 100%;
  box-sizing: border-box;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-tabs {
  margin-top: 20px;
}

.el-timeline {
  margin-top: 20px;
}

.order-dialog-content {
  padding: 0;
}

.order-dialog-content .search-area {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.order-dialog-content .el-table {
  margin-bottom: 16px;
}

.order-dialog-content .pagination-container {
  display: flex;
  justify-content: flex-end;
}

.code-preview-section {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.code-preview-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.preview-code {
  padding: 8px 12px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  color: #409eff;
  font-weight: 600;
}

/* 添加对话框内的表单和物品显示样式 */
.add-form-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f2f5;
}

.generate-items-section {
  margin-top: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.items-table-wrapper {
  background-color: #fafafa;
  border-radius: 4px;
  padding: 16px;
}

.items-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
